package by.pavlyukevich.paymentsystem.dataaccess.user.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.stereotype.Repository;

import by.pavlyukevich.paymentsystem.dataaccess.filter.ContractorFilter;
import by.pavlyukevich.paymentsystem.dataaccess.filter.Filter;
import by.pavlyukevich.paymentsystem.dataaccess.impl.AbstractDaoImpl;
import by.pavlyukevich.paymentsystem.dataaccess.user.ContractorDao;
import by.pavlyukevich.paymentsystem.datamodel.user.Contractor;
import by.pavlyukevich.paymentsystem.datamodel.user.Contractor_;

@Repository
public class ContractorDaoImpl extends AbstractDaoImpl<Integer, Contractor> implements
		ContractorDao {

	protected ContractorDaoImpl() {
		super(Contractor.class);
	}

	@Override
	public List<Contractor> getList(Filter<Contractor> contractorFilter) {
		CriteriaQuery<Contractor> criteria = getAllCriteria(contractorFilter);
		addCriteriaRestrict(criteria, contractorFilter);
		Root<Contractor> root = getRoot(criteria, Contractor.class);
		return getList(criteria, contractorFilter);
	}

	@Override
	public long getCount(Filter<Contractor> contractorFilter) {
		CriteriaQuery<Long> criteria = getCountAllCriteria();
		addCriteriaRestrict(criteria, contractorFilter);
		return getSingle(criteria);
	}

	private <T> CriteriaQuery<T> addCriteriaRestrict(CriteriaQuery<T> criteria,
			Filter<Contractor> filter) {
		if (filter == null) {
			return criteria;
		}
		Root<Contractor> root = getRoot(criteria, Contractor.class);
		CriteriaBuilder cBuilder = getEntityManager().getCriteriaBuilder();
		List<Predicate> predicateList = new ArrayList<Predicate>();
		ContractorFilter contractorFilter = (ContractorFilter) filter;
		if (contractorFilter.getName() != null) {
			predicateList
					.add(cBuilder.like(root.get(Contractor_.name), contractorFilter.getName()));
		}
		if (contractorFilter.getUnp() != null) {
			predicateList.add(cBuilder.equal(root.get(Contractor_.unp), contractorFilter.getUnp()));
		}

		if (predicateList.size() > 0) {
			Predicate predicateArray[] = predicateList.toArray(new Predicate[0]);
			criteria.where(predicateArray);
		}
		return criteria;
	}
}
